//
//  MyScrollView.m
//  测试
//
//  Created by dllo on 15/11/3.
//  Copyright © 2015年 Sky. All rights reserved.
//

#import "MyScrollView.h"
#import <UIImageView+WebCache.h>
#import "ZJHCaiPuScrollViewModel.h"
#import "FitHeader.h"
#import "FontSizeSingleTon.h"
#import "Adaptive.h"
#define Font [[FontSizeSingleTon shareFontSize]array]
@implementation MyScrollView
static NSTimer *timer;
static UIPageControl *pageContro;
static NSMutableArray *array;

- (instancetype)initWithFrame:(CGRect)frame imageArray:(NSArray *)imageArray pageC:(UIPageControl *)pageC
{
    if (self = [super initWithFrame:frame ]) {
        
        // 设置隐藏横向条
        self.showsHorizontalScrollIndicator = NO;
        self.pagingEnabled = YES;
        
        // 取消边缘反弹
        self.bounces = NO;
        // 设置自动分页
        self.pagingEnabled = YES;
        // 设置代理
        self.delegate = self;
        //初始化滚动视图数据数组
        array = [NSMutableArray arrayWithArray:imageArray];
        //初始化所有imageView(多两个)上数据数组
        _allDataArray = [NSMutableArray array];
        //设置偏移量
        self.contentOffset = CGPointMake(self.frame.size.width, 0);
        //设置大小
        self.contentSize = CGSizeMake(self.frame.size.width * (array.count + 2) , 0);
        
        pageContro = pageC;
        //创建图片
        [self createImage];
        
        
    }
    
    return self;
}

- (void)createImage {
    
    // 循环创建图片
    for (int i = 0; i < array.count + 2; i++)
    {
        //创建imageView
        UIImageView *imageView =  [[UIImageView alloc] initWithFrame:CGRectMake(i * self.frame.size.width, 0, self.frame.size.width, self.frame.size.height)];
        //给imageView添加手势
        imageView.userInteractionEnabled = YES;
        imageView.tag = 1000 + i;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction:)];
        [imageView addGestureRecognizer:tap];
        
        UILabel *lable = [[UILabel alloc]init];
        lable.font = [UIFont systemFontOfSize:[Font[2] integerValue]];
        lable.textAlignment = NSTextAlignmentCenter;
        lable.backgroundColor = [UIColor orangeColor];
        lable.layer.masksToBounds = YES;
        lable.layer.cornerRadius = 10 * ht ;
        lable.textColor = [UIColor whiteColor];
        [imageView addSubview:lable];
        if (i == 0) {
            
            ZJHCaiPuScrollViewModel *model = [array lastObject];
            [imageView sd_setImageWithURL:[NSURL URLWithString:model.Img]placeholderImage:[UIImage imageNamed:@"syzhanwei"]];
            CGFloat width = [Adaptive adaptiveWidthByString:model.Title Height:20 * ht FontSize: [Font[2]integerValue]] + 10 * wt;
            CGFloat x = (self.frame.size.width - width) / 2.0;
            lable.frame = CGRectMake(x, 200 * ht, width, 20 * ht);
            lable.text = model.Title;
            [_allDataArray addObject:model];
        }
        else if (i == array.count + 1) {
            ZJHCaiPuScrollViewModel *model = array[0];
            [imageView sd_setImageWithURL:[NSURL URLWithString:model.Img]placeholderImage:[UIImage imageNamed:@"syzhanwei"]];
            CGFloat width = [Adaptive adaptiveWidthByString:model.Title Height:20 * ht FontSize: [Font[2]integerValue]] + 10 * wt;
            CGFloat x = (self.frame.size.width - width) / 2.0;
            lable.frame = CGRectMake(x, 200 * ht, width, 20 * ht);
            lable.text = model.Title;
            [_allDataArray insertObject:model atIndex:i];
        }
        else {
            ZJHCaiPuScrollViewModel *model = array[i - 1];
            [imageView sd_setImageWithURL:[NSURL URLWithString:model.Img]placeholderImage:[UIImage imageNamed:@"syzhanwei"]];
            CGFloat width = [Adaptive adaptiveWidthByString:model.Title Height:20 * ht FontSize: [Font[2]integerValue]] + 10 * wt;
            CGFloat x = (self.frame.size.width - width) / 2.0;
            lable.frame = CGRectMake(x, 200 * ht, width, 20 * ht);
            lable.text = model.Title;
            [_allDataArray insertObject:model atIndex:i];
        }
        [self addSubview:imageView];
    }
    if (_allDataArray.count > 3) {
        [self addTimer];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    }
   
    [self pageControl];
}
#pragma mark 点击滚动视图跳转界面
-(void)tapAction:(UITapGestureRecognizer *)tap
{
    NSInteger index = tap.view.tag - 1000;
    ZJHCaiPuScrollViewModel *model = _allDataArray[index];
    NSString *str1 = model.Url;
    NSArray *array1 = [str1 componentsSeparatedByString:@"id="];
    NSString *str2 = array1[1];
    NSArray *array2 = [str2 componentsSeparatedByString:@"&"];
    NSString *string = array2[0];
    NSInteger receipId = [string integerValue];
    if ([model.Url hasSuffix:@"video=1"]) {
        [self.myDelegate scrollViewPushToVideoViewWithReceipId:string];
    }
    else
    {
        [self.myDelegate scrollViewPushToViewWithReceipId:receipId Title:model.Title];
    }
}
- (void)pageControl {
    
    //        // 显示页数
    pageContro.numberOfPages = array.count;
    //       // 显示当前页数
    pageContro.currentPage = 0;
    //
    //        // 非 当前页 点的颜色
    pageContro.pageIndicatorTintColor = [UIColor lightGrayColor];
    //        // 当前页 点的颜色
    pageContro.currentPageIndicatorTintColor = [UIColor greenColor];
    
}

#pragma mark - 滑动的时候调用
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    //计算页码
    //页码 = (contentOffset.x + scrollView一半宽度) / scrollView宽度
    if (scrollView == self) {
        
        if (scrollView.contentOffset.y == 0)
        {
            CGFloat scrollView_width = scrollView.frame.size.width;
            CGFloat x = scrollView.contentOffset.x - scrollView_width;
            int page = (x + scrollView_width / 2) / scrollView_width;
            if (page == array.count + 2 - 1) {
                page = 0;
            }
            pageContro.currentPage = page;
            
            
            if (self.contentOffset.x == self.frame.size.width * (array.count + 2 - 1)) {
                
                [self setContentOffset:CGPointMake(self.frame.size.width, 0) animated:NO];
            }
            
            if (self.contentOffset.x == 0) {
                
                [self setContentOffset:CGPointMake(self.frame.size.width * (array.count), 0) animated:NO];
            }
            
        }
        
    }
    
}

#pragma mark - 开启定时器
- (void)addTimer{
    
    /*
     定时器 适合用来隔一段时间做一些间隔较长的操作
     参数1.NSTimeInterval：多长时间操作一次
     参数2.target：操作谁
     参数3.selector：要操作的方法
     参数4.userInfo：传递参数
     参数5.repeats：是否重复
     */
    timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(update) userInfo:nil repeats:YES];
}

- (void)update
{
    
    int page = (int)pageContro.currentPage;
    
    if (page == array.count + 2 - 1) {
        page = 0;
    }else {
        page++;
    }
    
    //滚动scrollView
    CGFloat x = (page + 1) * self.frame.size.width;
    [self setContentOffset:CGPointMake(x, 0) animated:YES];
    
    // 根据x的偏移量判断 如果滚动到最后一张 取消滚动效果 变成第一张
    if (self.contentOffset.x == self.frame.size.width * (array.count + 2 - 1)) {
        
        [self setContentOffset:CGPointMake(x, 0) animated:NO];
        
    }
    
}
#pragma mark 拖拽定时器停止
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    if (_allDataArray.count > 3) {
    [timer invalidate];
    timer = nil;
    }
}
#pragma mark 停止拖拽添加定时器
-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    if (_allDataArray.count > 3) {
        [self addTimer];
        [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
    }
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
